package cn.iocoder.yudao.module.shop.framework;

import cn.iocoder.yudao.framework.datapermission.v1.UniDataPermissionRuleCustomizer;
import cn.iocoder.yudao.framework.datapermission.v1.UniDataPermissionScope;
import cn.iocoder.yudao.module.shop.admin.pojo.po.ShopUser;
import cn.iocoder.yudao.module.shop.diy.dal.dataobject.DiyPageDO;
import cn.iocoder.yudao.module.shop.diy.dal.dataobject.DiyTemplateDO;
import cn.iocoder.yudao.module.shop.info.dal.dataobject.ShopEnterOrderDO;
import cn.iocoder.yudao.module.shop.info.dal.dataobject.ShopInfoDO;
import cn.iocoder.yudao.module.shop.kefu.dal.dataobject.KeFuConversationDO;
import cn.iocoder.yudao.module.shop.kefu.dal.dataobject.KeFuMessageDO;
import cn.iocoder.yudao.module.shop.revenue.pojo.po.ShopRevenue;
import cn.iocoder.yudao.module.shop.staff.pojo.po.ShopStaff;
import cn.iocoder.yudao.module.shop.statistics.dal.dataobject.ShopStatisticsDO;
import jakarta.annotation.Nonnull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Set;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserShopIds;

/**
 * shop 模块的 permission 组件的配置类
 *
 * @author 山野羡民（1032694760@qq.com）
 */
@Configuration(proxyBeanMethods = false)
public class ShopDataPermissionConfiguration {

    @Bean
    public UniDataPermissionRuleCustomizer shopDataPermissionRuleCustomizer() {
        return rule -> {
            // shop 基于店铺的数据权限
            rule.addDataColumn(ShopInfoDO.class, "id", "shop_id"); // WHERE id = ?
            rule.addDataColumn(ShopUser.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(ShopEnterOrderDO.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(ShopStatisticsDO.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(ShopUser.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(DiyPageDO.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(DiyTemplateDO.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(KeFuConversationDO.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(KeFuMessageDO.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(ShopRevenue.class, "shop_id"); // WHERE shop_id = ?
            rule.addDataColumn(ShopStaff.class, "shop_id"); // WHERE shop_id = ?
        };
    }

    @Bean
    public UniDataPermissionScope shopDataPermissionScope() {
        return new UniDataPermissionScope() {
            @Nonnull
            @Override
            public String getScopeKey() {
                return "shop_id";
            }

            @Override
            public Set<Long> getScopeValues() {
                // 坑：这里只能通过登录上下文 LoginUser 获取，不能通过直接从数据库获取，
                // 否则会造成递归调用的死循环，触发异常：java.lang.StackOverflowError
                return getLoginUserShopIds();
            }
        };
    }

}
